<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { useMerchantStore } from "@/store";
import { ElMessage, ElMessageBox } from "element-plus";
import MerchantLayout from "@/components/merchant/MerchantLayout.vue";

const merchantStore = useMerchantStore();
const categories = ref<any[]>([]);
const loading = ref(false);

// 分类表单
const categoryForm = reactive({
  id: "",
  name: "",
  sort: 0,
});
const categoryDialogVisible = ref(false);
const isEdit = ref(false);
const formLoading = ref(false);

// 获取分类列表
const fetchCategories = async () => {
  if (!merchantStore.currentStoreId) {
    categories.value = [];
    return;
  }

  loading.value = true;
  try {
    // 从店铺详情API获取商品分类
    const { getCategories } = await import("@/api/merchant");
    const catRes = await getCategories(merchantStore.currentStoreId);

    console.log("获取商品分类响应:", catRes);

    // 设置分类数据
    categories.value = catRes || [];

    console.log("店铺分类数据:", categories.value);
  } catch (error) {
    console.error("获取分类列表失败", error);
    ElMessage.error("获取分类列表失败");
  } finally {
    loading.value = false;
  }
};

// 打开添加分类对话框
const openAddCategory = () => {
  isEdit.value = false;
  categoryForm.id = "";
  categoryForm.name = "";
  categoryForm.sort = 0;
  categoryDialogVisible.value = true;
};

// 打开编辑分类对话框
const openEditCategory = (row: any) => {
  isEdit.value = true;
  categoryForm.id = row.id;
  categoryForm.name = row.name;
  categoryForm.sort = row.sort || 0;
  categoryDialogVisible.value = true;
};

// 保存分类
const handleSaveCategory = async () => {
  if (!categoryForm.name) {
    ElMessage.warning("请输入分类名称");
    return;
  }

  if (!merchantStore.currentStoreId) {
    ElMessage.warning("未选择店铺");
    return;
  }

  formLoading.value = true;
  try {
    if (isEdit.value) {
      // 更新分类
      const { updateCategory } = await import("@/api/merchant");
      await updateCategory(merchantStore.currentStoreId, categoryForm.id, {
        name: categoryForm.name,
        sort: categoryForm.sort,
      });
      ElMessage.success("分类更新成功");
    } else {
      // 添加分类
      const { addCategory } = await import("@/api/merchant");
      await addCategory(merchantStore.currentStoreId, {
        name: categoryForm.name,
        sort: categoryForm.sort,
      });
      ElMessage.success("分类添加成功");
    }
    categoryDialogVisible.value = false;
    fetchCategories();
  } catch (error) {
    console.error("保存分类失败", error);
    ElMessage.error("保存失败");
  } finally {
    formLoading.value = false;
  }
};

// 删除分类
const handleDeleteCategory = async (row: any) => {
  try {
    await ElMessageBox.confirm("确定要删除该分类吗？删除后无法恢复", "提示", {
      type: "warning",
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    });

    if (!merchantStore.currentStoreId) {
      ElMessage.warning("未选择店铺");
      return;
    }

    loading.value = true;
    const { deleteCategory } = await import("@/api/merchant");
    await deleteCategory(merchantStore.currentStoreId, row.id);
    ElMessage.success("分类已删除");
    fetchCategories();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除分类失败", error);
      ElMessage.error("删除失败");
    }
  } finally {
    loading.value = false;
  }
};

// 编辑分类
const handleEditCategory = (row: any) => {
  categoryForm.id = row.id;
  categoryForm.name = row.name;
  categoryForm.sort = row.sort || 0;
  isEdit.value = true;
  categoryDialogVisible.value = true;
};

// 添加分类
const handleAddCategory = () => {
  categoryForm.id = "";
  categoryForm.name = "";
  categoryForm.sort = 0;
  isEdit.value = false;
  categoryDialogVisible.value = true;
};

onMounted(async () => {
  // 确保店铺信息已加载
  if (merchantStore.stores.length === 0) {
    await merchantStore.fetchStores();
  }

  // 获取分类列表
  await fetchCategories();
});

// 监听店铺变化
watch(() => merchantStore.currentStoreId, fetchCategories);
</script>

<template>
  <merchant-layout>
    <div class="categories-view">
      <el-card class="categories-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>分类管理</span>
            <el-button type="primary" size="small" @click="openAddCategory"
              >添加分类</el-button
            >
          </div>
        </template>
        <div v-if="!merchantStore.currentStoreId" class="no-store-tip">
          <el-empty description="请先选择店铺" />
        </div>
        <el-table
          v-else
          :data="categories"
          v-loading="loading"
          style="width: 100%"
          stripe
        >
          <el-table-column prop="name" label="分类名称" />
          <el-table-column prop="sort" label="排序" />
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button size="small" @click="openEditCategory(row)">
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDeleteCategory(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 分类表单对话框 -->
      <el-dialog
        v-model="categoryDialogVisible"
        width="400px"
        :show-close="false"
      >
        <template #header>
          <div class="custom-dialog-header">
            <span>{{ isEdit ? "编辑分类" : "添加分类" }}</span>
            <button
              class="custom-close-btn"
              @click="categoryDialogVisible = false"
              aria-label="关闭"
            >
              <el-icon><Close /></el-icon>
            </button>
          </div>
        </template>
        <el-form :model="categoryForm" label-width="80px">
          <el-form-item label="分类名称">
            <el-input
              v-model="categoryForm.name"
              placeholder="请输入分类名称"
            />
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number v-model="categoryForm.sort" :min="0" :max="999" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSaveCategory"
            :loading="formLoading"
            >确定</el-button
          >
        </template>
      </el-dialog>
    </div>
  </merchant-layout>
</template>

<style scoped>
.categories-view {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  height: 64px;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.store-selector {
  display: flex;
  align-items: center;
}

.store-selector .label {
  margin-right: 10px;
  color: #909399;
}

.el-main {
  padding: 20px;
}

.categories-card {
  border-radius: 18px;
  background: #fffbe7;
  box-shadow: 0 2px 8px #ffd54f33;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.no-store-tip {
  padding: 30px 0;
}
.custom-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  padding-right: 4px;
}
.custom-close-btn {
  border: none;
  background: #f5f6fa;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.2s, box-shadow 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-left: 8px;
}
.custom-close-btn:hover {
  background: #ffd54f;
  color: #a05a1c;
  box-shadow: 0 4px 16px rgba(255, 213, 79, 0.15);
}
</style>
